using Microsoft.AspNetCore.Mvc;
using WeatherSystem.API.Services.MessageQueue;
using WeatherSystem.API.Configurations;
using System.ComponentModel.DataAnnotations;

namespace WeatherSystem.API.Controllers
{
    /// <summary>
    /// 消息队列管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MessageQueueController : ControllerBase
    {
        private readonly IMessageQueueService _messageQueueService;
        private readonly IBusinessMetricsService _metricsService;
        private readonly ILogger<MessageQueueController> _logger;

        public MessageQueueController(
            IMessageQueueService messageQueueService,
            IBusinessMetricsService metricsService,
            ILogger<MessageQueueController> logger)
        {
            _messageQueueService = messageQueueService;
            _metricsService = metricsService;
            _logger = logger;
        }

        /// <summary>
        /// 发布天气数据采集任务
        /// </summary>
        [HttpPost("weather-collection")]
        public async Task<IActionResult> PublishWeatherCollectionTask([FromBody] PublishWeatherCollectionRequest request)
        {
            using var activity = _metricsService.StartActivity("publish_weather_collection_api");
            
            try
            {
                var task = new WeatherDataCollectionTask
                {
                    CityIds = request.CityIds,
                    Source = request.Source ?? "API",
                    Parameters = request.Parameters ?? new Dictionary<string, object>(),
                    UserId = User.Identity?.Name ?? "Anonymous",
                    Priority = request.Priority
                };

                await _messageQueueService.PublishWeatherDataCollectionTask(task);

                return Ok(new { 
                    TaskId = task.TaskId, 
                    Message = "天气数据采集任务已提交到队列",
                    CityCount = task.CityIds.Length
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布天气数据采集任务失败");
                return StatusCode(500, new { Message = "发布任务失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 发布批量数据处理任务
        /// </summary>
        [HttpPost("batch-processing")]
        public async Task<IActionResult> PublishBatchProcessingTask([FromBody] PublishBatchProcessingRequest request)
        {
            using var activity = _metricsService.StartActivity("publish_batch_processing_api");
            
            try
            {
                var task = new BatchDataProcessingTask
                {
                    OperationType = request.OperationType,
                    TargetIds = request.TargetIds,
                    Parameters = request.Parameters ?? new Dictionary<string, object>(),
                    UserId = User.Identity?.Name ?? "Anonymous",
                    BatchSize = request.BatchSize
                };

                await _messageQueueService.PublishBatchDataProcessingTask(task);

                return Ok(new { 
                    TaskId = task.TaskId, 
                    Message = "批量数据处理任务已提交到队列",
                    TargetCount = task.TargetIds.Length
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布批量数据处理任务失败");
                return StatusCode(500, new { Message = "发布任务失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 发布数据导出任务
        /// </summary>
        [HttpPost("data-export")]
        public async Task<IActionResult> PublishDataExportTask([FromBody] PublishDataExportRequest request)
        {
            using var activity = _metricsService.StartActivity("publish_data_export_api");
            
            try
            {
                var task = new DataExportTask
                {
                    ExportType = request.ExportType,
                    DataType = request.DataType,
                    Filters = request.Filters ?? new Dictionary<string, object>(),
                    Columns = request.Columns ?? Array.Empty<string>(),
                    UserId = User.Identity?.Name ?? "Anonymous",
                    CallbackUrl = request.CallbackUrl ?? ""
                };

                await _messageQueueService.PublishDataExportTask(task);

                return Ok(new { 
                    TaskId = task.TaskId, 
                    Message = "数据导出任务已提交到队列"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布数据导出任务失败");
                return StatusCode(500, new { Message = "发布任务失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 发布系统事件
        /// </summary>
        [HttpPost("system-event")]
        public async Task<IActionResult> PublishSystemEvent([FromBody] PublishSystemEventRequest request)
        {
            using var activity = _metricsService.StartActivity("publish_system_event_api");
            
            try
            {
                var eventMessage = new SystemEventMessage
                {
                    EventType = request.EventType,
                    Source = request.Source ?? "API",
                    Message = request.Message,
                    Data = request.Data ?? new Dictionary<string, object>(),
                    UserId = User.Identity?.Name ?? "Anonymous",
                    TraceId = HttpContext.TraceIdentifier
                };

                await _messageQueueService.PublishSystemEvent(eventMessage);

                return Ok(new { 
                    EventId = eventMessage.EventId, 
                    Message = "系统事件已发布到队列"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布系统事件失败");
                return StatusCode(500, new { Message = "发布事件失败", Error = ex.Message });
            }
        }
    }

    // 请求模型
    public class PublishWeatherCollectionRequest
    {
        [Required]
        public string[] CityIds { get; set; } = Array.Empty<string>();
        
        public string? Source { get; set; }
        
        public Dictionary<string, object>? Parameters { get; set; }
        
        [Range(1, 5)]
        public int Priority { get; set; } = 1;
    }

    public class PublishBatchProcessingRequest
    {
        [Required]
        public string OperationType { get; set; } = "";
        
        [Required]
        public string[] TargetIds { get; set; } = Array.Empty<string>();
        
        public Dictionary<string, object>? Parameters { get; set; }
        
        [Range(1, 1000)]
        public int BatchSize { get; set; } = 100;
    }

    public class PublishDataExportRequest
    {
        [Required]
        public string ExportType { get; set; } = "";
        
        [Required]
        public string DataType { get; set; } = "";
        
        public Dictionary<string, object>? Filters { get; set; }
        
        public string[]? Columns { get; set; }
        
        public string? CallbackUrl { get; set; }
    }

    public class PublishSystemEventRequest
    {
        [Required]
        public string EventType { get; set; } = "";
        
        public string? Source { get; set; }
        
        [Required]
        public string Message { get; set; } = "";
        
        public Dictionary<string, object>? Data { get; set; }
    }
}